import React, { useState, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { getProductCategoryList, deleteProductCategory, upProductCategory, downProductCategory } from '@/api/assetMaintain/dataProduct'
import { message, usePage } from '@hs-admin/utils'
import { Button, Flex, Popconfirm, Space, Form } from 'antd'
import { HsAdminForm, HsAdminSpin, HsAdminTablePage } from '@hs-admin/base-components'
import EditModal from './ParentEdit'
import MoveSort from '@/components/global/NewMoveSort'
import { handleButtonShow } from '@/utils/tools'

interface Props {
  source: 'item_set' | 'website'
}
const OperationDataProduct: React.FC<Props> = (props: Props) => {
  const { source } = props
  const navigate = useNavigate()
  const { pagination, resetPage }: { pagination: UsePageProps; resetPage: () => void } = usePage(callList)
  const [data, setdata] = useState<any[]>([])
  const editRef = useRef<any>(null)
  const [form] = Form.useForm()
  const formItemOptions = [
    {
      label: '产品名称',
      name: 'keywords',
      component: 'Input',
      componentProps: {
        onPressEnter: searchList
      }
    }
  ]
  const [loading, setloading] = useState(true)

  function moveUp(record: any) {
    upProductCategory({ id: record.id }).then(() => {
      message.success('上移成功')
      callList()
    })
  }
  function moveDown(record: any) {
    downProductCategory({ id: record.id })
      .then(() => {
        message.success('下移成功')
        callList()
      })
      .finally(() => {})
  }
  function reset() {
    form.resetFields()
    resetPage()
    callList()
  }
  function searchList() {
    resetPage()
    callList()
  }
  function callList() {
    setloading(true)
    const fieldsValues = form.getFieldsValue()
    return getProductCategoryList({
      ...fieldsValues,
      page: pagination.current,
      page_size: pagination.pageSize,
      category: source
    }).then((res) => {
      setdata(res.items ?? [])
      setloading(false)
      return res
    })
  }
  const columns = [
    {
      title: '移动',
      dataIndex: 'move',
      width: 120,
      render: (_text: string, record: any, index: number) => (
        <MoveSort pagination={pagination} record={record} index={index} data={data} moveUp={moveUp} moveDown={moveDown} />
      )
    },
    {
      title: '类别名称',
      dataIndex: 'name',
      render: (text: string, record: any) => (
        <Button
          type="link"
          onClick={() => {
            if (source === 'website') {
              navigate(`/website/list?id=${record.id}&label=${record.name}`)
            } else {
              navigate(`/itemSet/list?id=${record.id}&label=${record.name}`)
            }
          }}>
          {text}
        </Button>
      )
    },
    {
      title: '描述',
      dataIndex: 'description',
      ellipsis: true
    },
    {
      title: '创建人',
      dataIndex: 'owner.name'
    },
    {
      title: '最新维护时间',
      dataIndex: 'updated_at',
      type: 'datetime'
    },
    {
      title: '操作',
      key: 'actions',
      render: (_text: string, record: any) => (
        <Flex gap="small">
          {handleButtonShow('datashop.product.update') && (
            <Button
              type="link"
              onClick={() => {
                editRef.current.showModal(record, source)
              }}>
              编辑
            </Button>
          )}
          {handleButtonShow('datashop.product.delete') && (
            <Popconfirm
              title="警告"
              description="确定删除该项吗?"
              onConfirm={async () => {
                deleteProductCategory({ id: record.id })
                  .then(() => {
                    message.success('删除成功')
                    searchList()
                  })
                  .finally(() => {})
              }}>
              <Button type="link">删除</Button>
            </Popconfirm>
          )}
        </Flex>
      )
    }
  ]
  const add = () => {
    editRef.current.showModal(null, source)
  }

  return (
    <div className="pr-4 pl-4 mt-4">
      {loading && <HsAdminSpin />}
      <Flex justify="space-between">
        <HsAdminForm form={form} formItemOptions={formItemOptions} />
        <Space>
          <Button onClick={reset}>重置</Button>
          <Button type="primary" onClick={searchList}>
            查询
          </Button>
        </Space>
      </Flex>
      <br />
      <Flex justify="space-between" align="center">
        <h3>产品类别</h3>
        {handleButtonShow('datashop.product.create') && (
          <Button type="primary" onClick={add}>
            新增
          </Button>
        )}
      </Flex>
      <br />
      <HsAdminTablePage columns={columns} dataSource={data} pagination={pagination} rowKey="id"></HsAdminTablePage>
      <EditModal ref={editRef} finish={searchList} />
    </div>
  )
}

export default OperationDataProduct
